package com.company.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: 同步机制之 ： veresion1: synchronized-wait-notify    version2: lock-await-signal   version3: blcokingqueue-atom*-信号量
 * @author: ruoan
 * @date: 2020/12/12 8:58
 */
public class SyncVersion2 {

    public static void main(String[] args) {

        MyResource2 myResource = new MyResource2();
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                try {
                    myResource.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, String.valueOf(i)).start();
        }

        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                try {
                    myResource.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, String.valueOf(i)).start();
        }

    }
}
@Slf4j
class MyResource2 {

    private int num = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    /**
     * 加1方法
     */
    void increment() throws InterruptedException {
        lock.lock();
        try {
            // num为1时候进入循环
            while (num != 0) {
                condition.await();
            }
            num++;
            log.info(Thread.currentThread().getName() + "\t increment()");
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }



    }
    /**
     * 减1方法
     */
    void decrement() throws InterruptedException {

        lock.lock();
        try {
            // 当num==0进入循环体等待
            while (num == 0) {
                condition.await();
            }
            num--;
            log.info(Thread.currentThread().getName() + "\t decrement()");
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


    }

}